#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""诗词对象类
主要建立诗词属性结构
"""
from numpy import random
from Base import Base


class PoetryModel(Base):
    def __init__(self, full_name, list_poetry, dynasty, flower_orders, new_flower_orders, idioms):
        # 输入一首list格式的诗词内容，前四个元素为标题、副标题、作者、朝代，后边为句子。
        super(PoetryModel, self).__init__()
        # 诗词属性
        self.title = ""  # 【字符串】诗词名称
        self.second_title = ""  # 【字符串】子名称，当诗为组诗或词牌名相同的多首词时使用
        self.author = ""  # 【字符串】作者
        self.dynasty = dynasty  # 【字符串】朝代
        self.full_name = full_name  # 组合好的诗词全名
        self.recite = 0  # 【int】背诵等级
        self.poetry_note = {}  # 【字典】诗的赏析，key为赏析的角度，包括“常规”“典故”“扩展”等
        self.flower_orders = flower_orders  # 【集合】存放飞花令题目的字
        self.new_flower_orders = new_flower_orders  # 【字典】存放新飞花令题目的组合
        self.idioms = idioms  # 【集合】存放可以使用的成语
        # 题目组合
        self.questions_flower_order = []  # 【字典的集合】存放飞花令产生的题目
        self.question_new_flower_order = []  # 【字典的组合】存放新飞花令产生的题目
        self.question_idiom = []  # 【字典的组合】存放多个成语产生的题目
        self.tag = []  # 【集合】存放这首诗的标签
        # 句子属性
        self.sentences = {}  # 【字典】内容，句子顺序号为key，内容为每句，根据元素位置单双号判断其是上句还是下句。
        self.sentences_note = {}  # 【字典】句子注释，使用句子顺序号key与句子对应。
        self.word_note = {}  # 【字典】句子中词的注释，使用句子顺序号key与句子对应，value是子字典，key为词，value为注释。
        self.question_type_list = []
        # 通过初始化传入的list初始化诗词
        self.load_from_list(list_poetry)

    def load_from_list(self, list_poetry):
        self.title = list_poetry[0]
        self.second_title = list_poetry[1]
        self.author = list_poetry[2]
        self.recite = 0
        for i in range(3, len(list_poetry)):
            self.sentences[i - 2] = list_poetry[i]
        # 获取飞花令题目
        self.get_flower_orders_list()
        # 获取新飞花令题目
        self.get_new_flower_orders_list()
        # 获取成语组句题目
        self.get_idiom_list()
        # 获取问题属性
        self.get_question_type_list()

    def print_content(self, print_level=4):
        """
        print_level:
        0 打印诗歌本身
        1  打印诗歌和解释
        2  打印诗歌解释和赏析
        3  打印诗歌所有信息
        打印这首诗
        :return:
        """
        print("--*--" + self.title + "." + self.second_title + "--*--")
        print("作者：" + self.author)
        print("朝代：" + self.dynasty)
        for content_item in self.sentences:
            print(str(content_item) + " " + self.sentences[content_item])
            if print_level > 0:
                for word_item in self.word_note[content_item]:
                    print(word_item + ":" + self.word_note[content_item][word_item])
                print(self.sentences_note[content_item])
        if print_level > 1:
            for poetry_note_item in self.poetry_note:
                print(poetry_note_item + "：" + self.poetry_note[poetry_note_item])
        if print_level > 2:
            for question_item in self.questions_flower_order:
                print(question_item["no"])
                print(question_item["question"])
                print(question_item["answer"])

    # 获取诗词内容
    def get_content(self):
        content = self.full_name
        i = 1
        for content_item in self.sentences:
            i = i + 1
            if i % 2 == 0:
                content = content + "\n" + self.sentences[content_item]
            else:
                content = content + self.sentences[content_item]
        return content

    # 获取随机题目类型集合
    def get_question_type_list(self):
        for key in self.cfg['question_type']:
            if key == 'get_content':
                if self.cfg.getboolean('question_type', key) and self.sentences.__len__() < 11:
                    self.question_type_list.append(key)
            elif key == 'get_sentence_by_flower_order':
                if self.cfg.getboolean('question_type', key) and self.questions_flower_order:
                    self.question_type_list.append(key)
            elif key == 'get_sentence_by_new_flower_order':
                if self.cfg.getboolean('question_type', key) and self.question_new_flower_order:
                    self.question_type_list.append(key)
            elif key == 'get_sentence_by_idiom':
                if self.cfg.getboolean('question_type', key) and self.question_idiom:
                    self.question_type_list.append(key)
            else:
                if self.cfg.getboolean('question_type', key):
                    self.question_type_list.append(key)

    # 获取飞花令题目集合
    def get_flower_orders_list(self):
        question = {}
        for word in self.flower_orders:
            bool_sen = False
            for no in self.sentences:
                if word in self.sentences[no]:
                    if not bool_sen:
                        question = ({"no": self.full_name})
                        bool_sen = True
                        question["question"] = "请说出" + self.full_name + '中带【' + word + '】字的任意一句'
                        question["answer"] = self.sentences[no][:-1]
                    else:
                        question["answer"] = question["answer"] + '\n' + self.sentences[no][:-1]
            if bool_sen:
                self.questions_flower_order.append(question)

    # 获取新飞花令题目集合
    def get_new_flower_orders_list(self):
        question = {}
        for key in self.new_flower_orders:
            bool_sen = False
            for no in self.sentences:
                for word in self.new_flower_orders[key]:
                    if word in self.sentences[no]:
                        if not bool_sen:
                            question = ({'no': self.full_name})
                            bool_sen = True
                            question["question"] = "请说出" + self.full_name + '中带【' + key + '】的一句'
                            question["answer"] = self.sentences[no][:-1]
                        else:
                            if self.sentences[no][:-1] not in question["answer"]:
                                question["answer"] = question["answer"] + '\n' + self.sentences[no][:-1]
            if bool_sen:
                self.question_new_flower_order.append(question)

    # 获取成语组句题目集合
    def get_idiom_list(self):
        # question = {}
        for key in self.sentences:  # 选每一句诗
            idiom_list = []
            for word in list(self.sentences[key][:-1]):  # 将诗中每个字分解出来匹配成语
                idioms_temp = []  # 存储可用于这一个字的成语
                for idiom in self.idioms:
                    if word in idiom and idiom not in idiom_list:
                        idioms_temp.append(idiom)
                if not idioms_temp:
                    continue
                else:
                    idiom_list.append(random.choice(idioms_temp))
            if len(self.sentences[key][:-1]) == len(idiom_list):
                question = ({'no': self.full_name})
                question['question'] = '请从以下每条成语中选一个字组成一句诗（成语数量即这句诗的字数）'
                if self.cfg.getboolean('question_type_item', 'get_sentence_by_idiom_random'):
                    while idiom_list:
                        idiom = random.choice(idiom_list)
                        question['question'] = question['question'] + '\n' + idiom
                        idiom_list.remove(idiom)
                else:
                    for i in range(0, idiom_list.__len__()):
                        question['question'] = question['question'] + '\n' + idiom_list[i]
                question['answer'] = self.sentences[key][:-1]
                self.question_idiom.append(question)

    # 方便生成问题调用，只需要根据类型编号即可调用相应类型问题生成。
    def question(self):
        if not self.question_type_list:
            return None
        question_type = random.choice(self.question_type_list)
        question = {}
        if question_type == 'get_content':
            question = self.question_get_content()
        elif question_type == 'get_title_author_by_sentence':
            question = self.question_get_title_author_by_sentence()
        elif question_type == 'get_sentence':
            question = self.question_get_sentence()
        elif question_type == 'get_fill_word':
            question = self.question_fill_word()
        elif question_type == 'get_head_sentence':
            question = self.question_get_head_sentence()
        elif question_type == 'get_sentence_by_author_word':
            question = self.question_get_sentence_by_author_word()
        elif question_type == 'get_last_sentence':
            question = self.question_get_last_sentence()
        elif question_type == 'get_sentence_by_flower_order':
            question = random.choice(list(self.questions_flower_order))
        elif question_type == 'get_sentence_by_new_flower_order':
            question = random.choice((list(self.question_new_flower_order)))
        elif question_type == 'get_sentence_by_idiom':
            question = random.choice(list(self.question_idiom))
        question['subject'] = 'poetry_content'
        question['explain'] = self.get_content()
        return question

    # 列出诗名和作者问全文
    def question_get_content(self):
        question = ({"no": self.full_name})
        question["question"] = "背诵" + self.full_name
        contents = ""
        for i in range(1, int(self.sentences.__len__() / 2) + 1):
            contents = contents + self.sentences[i * 2 - 1] + self.sentences[i * 2] + "\n"
        question["answer"] = contents
        return question

    # 列出一句诗问诗名和作者
    def question_get_title_author_by_sentence(self):
        question = ({"no": self.full_name})
        two = self.get_two_sentence()
        sentences = ""
        for item in two.values():
            sentences = sentences + item
        question["question"] = "【" + sentences + "】是哪个作者哪首诗中的句子？"
        question["answer"] = self.full_name
        return question

    # 列出一句诗问上句或者下句
    def question_get_sentence(self):
        question = ({"no": self.full_name})
        sentence_no = random.randint(2, len(self.sentences) + 1)
        if (sentence_no % 2) == 0:
            question["question"] = "【" + self.sentences[sentence_no] + "】的上一句是？"
            question["answer"] = self.full_name + "\n" + self.sentences[sentence_no - 1] + self.sentences[sentence_no]
        else:
            question["question"] = "【" + self.sentences[sentence_no] + "】的下一句是？"
            question["answer"] = self.full_name + "\n" + self.sentences[sentence_no] + self.sentences[sentence_no + 1]
        return question

    # 列出两句诗填字
    def question_fill_word(self):
        question = ({"no": self.full_name})
        two = self.get_two_sentence()
        sentences = ""
        for item in two.values():
            sentences = sentences + item
        word_nos = []
        while word_nos.__len__() < 4:
            i = random.randint(0, len(sentences))
            if i in word_nos:
                continue
            word_nos.append(i)
        sentences_list = list(sentences)  # 只有转换成列表才能替换其中的字符
        for i in word_nos:
            word_fill = sentences[i]
            if word_fill not in ["，", "。", "？", "！"]:
                sentences_list[i] = "□"
        sentences_q = ''.join(sentences_list)
        question["question"] = "填字：【" + sentences_q + "】"
        question["answer"] = self.full_name + "\n" + sentences
        return question

    # 给诗词名称作者问诗的前两句
    def question_get_head_sentence(self):
        question = {"question": "背诵" + self.full_name + "的前两句", "answer": self.sentences[1] + self.sentences[2],
                    "no": self.full_name}
        return question

    # 给诗词名称和作者问诗的后两句
    def question_get_last_sentence(self):
        question = {"question": "背诵" + self.full_name + "的最后两句",
                    "answer": self.sentences[len(self.sentences) - 1] + self.sentences[len(self.sentences)],
                    "no": self.full_name}
        return question

    # 给出作者和诗句中的两个字问一句诗
    def question_get_sentence_by_author_word(self):
        two = self.get_two_sentence()
        one = random.choice(list(two.values()))[:-1]
        sentences = ""
        for item in two.values():
            sentences = sentences + item
        one_list = list(one)
        j = len(one_list)
        while True:
            i = random.randint(0, len(one_list))
            if one[i] not in ["，", "。", "？", "！"]:
                break
        if one_list.__len__() > 5:
            while True:
                j = random.randint(0, len(one_list))
                if one[j] not in ["，", "。", "？", "！"] and j != i:
                    break
        for n in range(0, one_list.__len__()):
            if n == i:
                continue
            if one_list.__len__() > 5 and n == j:
                continue
            one_list[n] = "□"
        one = ''.join(one_list)

        question = {"question": "补全【" + self.author + '】的诗句：' + one, "answer": self.full_name + "\n" + sentences,
                    "no": self.full_name}
        return question

    # 随机获取诗中两句连续的句子
    def get_two_sentence(self):
        sentence_no = random.randint(1, len(self.sentences) + 1)
        if (sentence_no % 2) == 0:
            sentence_no = sentence_no - 1
        two = {sentence_no: self.sentences[sentence_no], sentence_no + 1: self.sentences[sentence_no + 1]}
        return two

    # 获取该诗词所有的问题
    def get_all_questions(self):
        all_questions = []
        # 加载[获取全诗内容（超过十句不加载）]题目
        if 'get_content' in self.question_type_list:
            question = self.question_get_content()
            question['type'] = 'get_content'
            all_questions.append(question)
        # 加载[通过句子问题目和作者]题目
        if 'get_title_author_by_sentence' in self.question_type_list:
            question_list = []
            for i in range(0, self.sentences.__len__(), 2):
                question = {'no': self.full_name,
                            'question': "【" + self.sentences[i + 1] + self.sentences[i + 2] + "】是哪个作者哪首诗中的句子？",
                            'answer': self.full_name,
                            'type': 'get_title_author_by_sentence'}
                question_list.append(question)
            all_questions = all_questions + question_list
        # 加载[接上下句]题目
        if 'get_sentence' in self.question_type_list:
            question_list = []
            for i in range(0, self.sentences.__len__(), 2):
                question = {'no': self.full_name,
                            'question': "请说出【" + self.sentences[i + 1] + "】的下一句？",
                            'answer': self.sentences[i + 2],
                            'type': 'get_sentence'}
                question_list.append(question)
                question = {'no': self.full_name,
                            'question': "请说出【" + self.sentences[i + 2] + "】的上一句？",
                            'answer': self.sentences[i + 1],
                            'type': 'get_sentence'}
                question_list.append(question)
            all_questions = all_questions + question_list
        # 加载[句子填字]题目
        if 'get_fill_word' in self.question_type_list:
            question_list = []
            for i in range(0, self.sentences.__len__(), 2):
                sentences = self.sentences[i + 1] + self.sentences[i + 2]
                sentences_list = list(sentences)
                word_nos = []
                while word_nos.__len__() < 4:
                    i = random.randint(0, len(sentences_list))
                    if i in word_nos or sentences[i] in ["，", "；", "。", "？", "！"]:
                        continue
                    word_nos.append(i)
                    sentences_list[i] = "□"
                sentences_q = ''.join(sentences_list)
                word_nos.sort()
                words = ""
                for j in word_nos:
                    words = words + sentences[j] + ' '
                question = {'no': self.full_name,
                            'question': "填字：【" + sentences_q + "】",
                            'answer': self.full_name + "\n" + words[:-1],
                            'type': 'get_fill_word'}
                question_list.append(question)
            all_questions = all_questions + question_list
        # 加载[问诗词最前边两句]题目
        if 'get_head_sentence' in self.question_type_list:
            question = self.question_get_head_sentence()
            question['type'] = 'get_head_sentence'
            all_questions.append(question)
        # 加载[根据作者和部分字猜诗句]题目 等加入提示句之后再完成此功能
        if 'get_sentence_by_author_word' in self.question_type_list:
            pass
        # 加载[问诗句最后边两句]题目
        if 'get_last_sentence' in self.question_type_list:
            question = self.question_get_last_sentence()
            question['type'] = 'get_last_sentence'
            all_questions.append(question)
        # 加载[飞花令题目]题目
        if 'get_sentence_by_flower_order' in self.question_type_list:
            question_list = []
            for question in self.questions_flower_order:
                question['type'] = 'get_sentence_by_flower_order'
                question_list.append(question)
            all_questions = all_questions + question_list
        # 加载[新飞花令题目]题目
        if 'get_sentence_by_new_flower_order' in self.question_type_list:
            question_list = []
            for question in self.question_new_flower_order:
                question['type'] = 'get_sentence_by_new_flower_order'
                question_list.append(question)
            all_questions = all_questions + question_list
        # 加载[成语猜诗句题目]题目
        if 'get_sentence_by_idiom' in self.question_type_list:
            question_list = []
            for question in self.question_idiom:
                question['type'] = 'get_sentence_by_idiom'
                question_list.append(question)
            all_questions = all_questions + question_list
        # 加注释
        for question in all_questions:
            question['explain'] = self.get_content()
        return all_questions

    # 搜索该诗词是否符合条件
    def select_from_poetry(self, select_str, model):
        if model not in ['title', 'author', 'dynasty', 'content', 'new_flowers', 'tag']:
            self.error('搜索模式[' + model + ']错误！')
        result = []
        if model == 'title':
            if select_str in self.title or select_str in self.second_title:
                result = [self.full_name]
        elif model == 'author':
            if select_str in self.author:
                result = [self.full_name]
        elif model == 'dynasty':
            if result in self.dynasty:
                result = [self.full_name]
        elif model == 'content':
            for no in self.sentences:
                if select_str in self.sentences[no]:
                    result.append(self.full_name + ': ' + self.sentences[no][:-1])
        elif model == 'tag':
            if select_str in self.tag:
                result = [self.full_name]
        elif model == 'new_flowers':
            if select_str not in list(self.new_flower_orders):
                self.error('[' + select_str + ']不是新飞花令中的一个类型！')
            for no in self.sentences:
                for word in self.new_flower_orders[select_str]:
                    if word in self.sentences[no]:
                        if self.full_name + ': ' + self.sentences[no][:-1] not in result:
                            result.append(self.full_name + ': ' + self.sentences[no][:-1])
        return result
